﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIBase : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler {

    [SerializeField]
    protected bool isCanDrag;
    protected RectTransform rectTransform;
    protected bool isDragging;

    Vector2 beginOffset;

    protected virtual void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    protected virtual void Start()
    {
        LocalizeInit();
    }

    protected virtual void LocalizeInit() {

        Text[] texts = GetComponentsInChildren<Text>();
        if (texts.Length > 0)
        {
            for (int i = 0; i < texts.Length; i++)
            {
                Text text = texts[i];
                if (!string.IsNullOrEmpty(text.text) && LocalizationManager.Instance.IsCurrentValueExistKey(text.text))
                {
                    string vl = LocalizationManager.Instance.GetCurrentValueWithKey(text.text);
                    if (!string.IsNullOrEmpty(vl))
                        text.text = vl;
                }
            }
        }

    }

    public virtual void OnBeginDrag(PointerEventData eventData)
    {
        if (isCanDrag)
        {
            isDragging = true;

            Vector2 uiPos = rectTransform.anchoredPosition;
            Vector2 anchorPosWithMouse;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform.parent as RectTransform, eventData.position, eventData.pressEventCamera, out anchorPosWithMouse);
            beginOffset = anchorPosWithMouse - uiPos;
        }
    }

    public virtual void OnDrag(PointerEventData eventData)
    {
        if (isCanDrag)
        {
            Vector2 anchorPosWithMouse;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform.parent as RectTransform, eventData.position, eventData.pressEventCamera, out anchorPosWithMouse);
            rectTransform.anchoredPosition = anchorPosWithMouse - beginOffset;
        }
    }

    public virtual void OnEndDrag(PointerEventData eventData)
    {
        if (isCanDrag)
        {
            isDragging = false;
        }
    }
}
